/**
 * Created by XWang on 2018-06-20
 */
var request = require("superagent");
var API = require("./support/const");
var service = require("../../service/log");


//导出excel通用方法，
function exportExcel(req, res, header, params, api, type) {
    request.get(api)
        .set(header)
        .responseType("blob")
        .query({msg: JSON.stringify(params)})
        .end(function (_req, _res) {


            if (_res.status === 200) {
                service.save_user_log({'type': 'getList', 'msg': '导出' + type + '列表'}, req);
            }
            //导出型api, 返回文件流，在_res.body中, 而不在_res.text中
            //_res.body有可能是文件内容，也可能是错误信息
            var buffer = Buffer.from(_res.body);
            if (_res.header["content-type"]) {
                res.setHeader('Content-Type', _res.header["content-type"]);
            }
            if (_res.header["content-disposition"]) {
                res.setHeader('content-disposition', _res.header["content-disposition"]);
            }

            res.end(buffer);
        });
}


/**
 * 客户
 * **/
exports.customer = {
    list: function (req, res, next) {
        let header = {
            token: req.cookies.token
        };
        let params = req.body;
        request.get(API.customer.list)
            .set(header)
            .query({msg: JSON.stringify(params)})
            .end(function (_req, _res) {
                if (_res.status === 200) {
                    service.save_user_log({'type': 'getList', 'msg': '获取客户列表'}, req);
                }
                res.json(JSON.parse(_res.text));
            });
    },

    info: function (req, res, next) {
        let {id} = req.body;
        let header = {
            token: req.cookies.token
        };
        //let params = req.body;


        request.get(API.customer.info + id)
            .set(header)
            .query({msg: JSON.stringify({"id":id})})
            .end(function (_req, _res) {
                if (_res.status === 200) {
                    service.save_user_log({'type': 'getId', 'msg': '获取客户详情'}, req);
                }
                res.json(JSON.parse(_res.text));
            });
    },

    export: function (req, res, next) {
        let params = req.body;
        let header = {
            token: req.cookies.token
        };
        let api = API.customer.export;
        exportExcel(req, res, header, params, api, "客户");
    }
};
